import React from 'react'
import { inject } from 'mobx-react';

import './index.scss';

import { Button, Radio, Icon, Checkbox, message, Modal } from 'antd';


import Service from "@src/service"

//字符串转base64
function encode(str) {
    // 对字符串进行编码
    var encode = encodeURI(str);
    // 对编码的字符串转化base64
    var base64 = btoa(encode);
    return base64;
}


@inject('baseStore')
@inject('showStore')
@inject('createStore')
class loginPage extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            searchHistoryArr: (localStorage.getItem('search_keys') || '').split(','),
            ShuTiList: [{
                DirectoryName: '全部',
                DirectoryID: '',
                active: false
            }],
            ShuJiaList: [{
                DirectoryName: '全部',
                ItemId: '',
                active: false
            }, {
                DirectoryName: '单字',
                ItemId: '1',
                active: false
            }, {
                DirectoryName: '二字',
                ItemId: '2',
                active: false
            }, {
                DirectoryName: '三字',
                ItemId: '3',
                active: false
            }, {
                DirectoryName: '四字',
                ItemId: '4',
                active: false
            }, {
                DirectoryName: '五字',
                ItemId: '5',
                active: false
            }, {
                DirectoryName: '六字',
                ItemId: '6',
                active: false
            }, {
                DirectoryName: '七字',
                ItemId: '7',
                active: false
            }, {
                DirectoryName: '八字',
                ItemId: '8',
                active: false
            }, {
                DirectoryName: '多字',
                ItemId: '9',
                active: false
            }],
            typeList: [
                {
                    name: '我的创作',
                    placeholder: '作品名后回车执行搜索'
                },
                {
                    name: '名家作品',
                    placeholder: '作品名后回车执行搜索'
                }
                //     {
                //     name: '单字',
                //     placeholder: '例：厚德载物[或] hou de zai wu   |  输入后回车执行搜索'
                // }, {
                //     name: '笔画',
                //     placeholder: '例：横折钩[或] heng zhe gou    |  输入后回车执行搜索'
                // }, {
                //     name: '偏旁边',
                //     placeholder: '例：单人帝[或] dai ren pang    |  输入后回车执行搜索'
                // }
            ],
            typeIndex: 0, //单字|笔画|偏旁边
            searchInputValue: '',
            activeShuTiIndex: 0,
            activeShuJiaIndex: 0,
            searchResultList: [],
            show_edit: false,
            editEntity: null
        }
    }

    setArrActive = (arr, b) => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'setArrActive',
                param: [arr, b]
            }
        });

        arr.forEach((item) => {
            item['Active'] = b;
        })
    }

    pageChangeNoticeToServer = () => {
        var data = {
            header: this.props.baseStore.socketData.header,
            body: {
                type: "page_change",
                content: "/entry_04"
            }
        };
        //给服务端发送 sendMsg事件名的消息
        this.props.baseStore.socketData.socket.emit("teach_app_to_server", data);
    }

    componentWillMount() {

        this.pageChangeNoticeToServer()
        this.props.baseStore.socketData.currentReactView = this;

        this.props.baseStore.topHeader.title = "集字创作";
        this.props.baseStore.topHeader.show = true;
        this.props.baseStore.topHeader.backTo = '/entry';


        var that = this;
        Service.GetFuShiList().then(res => {
            console.log(res, "===========GetShuTiList========");
            console.log(res.length, "===========list.length========");
            that.setArrActive(res, false);
            that.setState({
                ShuTiList: this.state.ShuTiList.concat(res)
            });
        })

        // Service.GetShuJiaList().then(res => {
        //     console.log(res, "===========GetShuJiaList========");
        //     console.log(res.length, "===========list.length========");
        //     that.setArrActive(res, false);
        //     that.setState({
        //         ShuJiaList: this.state.ShuJiaList.concat(res)
        //     });
        // })

        that.Search();

    }

    componentWillUnmount = () => {
        this.setState = (state, callback) => {
            return;
        };
    }

    handleEnterKey = (e) => {
        if (e.nativeEvent.keyCode === 13) { //e.nativeEvent获取原生的事件对像
            this.Search()
        }
    }

    Search = (needSocket) => {
        var that = this;

        if (needSocket == undefined) {
            needSocket = true
        }

        needSocket && this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'Search',
                param: [false]
            }
        });

        var searhKey = this.state.searchInputValue || '';
        // if (searhKey === "") {
        //     message.info("请先搜索关键字");
        //     return false;
        // }

        //记录搜索历史  逗号分开
        // var arr = this.state.searchHistoryArr; //上面已经取出
        // if (arr.length >= 3) {
        //     arr = arr.slice(arr.length - 2, arr.length);
        // }
        // arr.push(searhKey);

        // that.setState({
        //     searchHistoryArr: arr
        // })
        // localStorage.setItem('search_keys', arr.join(','))


        var param = {
            "DirectoryName": "",
            "WordPageFormatId": "",
            "CalligrapherId": "",
            "WordNumId": ""
        }

        // if (this.state.typeIndex == 0) {
        //     param.DirectoryName = searhKey;
        // }

        param.DirectoryName = searhKey;





        if (this.state.typeIndex == 0) {

            if (this.state.activeShuTiIndex > 0) {
                var index = this.state.activeShuTiIndex;
                param.WordPageFormatId = this.state.ShuTiList[index].DirectoryID;
            }

            if (this.state.activeShuJiaIndex > 0) {
                var index = this.state.activeShuJiaIndex;
                param.WordNumId = this.state.ShuJiaList[index].ItemId;
            }

            Service.GetLinmoWordList(param).then(list => {



                console.log(list, "========GetJZPracticeList.res=============");

                that.AdjustSearchResultItem(list);

                that.setState({
                    searchResultList: list
                })
            })
        } else {

            if (this.state.activeShuTiIndex > 0) {
                var index = this.state.activeShuTiIndex;
                param.WordPageFormatId = this.state.ShuTiList[index].DirectoryID;
            }

            if (this.state.activeShuJiaIndex > 0) {
                var index = this.state.activeShuJiaIndex;
                param.WordNum = this.state.ShuJiaList[index].ItemId;
            }

            Service.GetFameworksList(param).then(list => {



                console.log(list, "========GetJZPracticeList.res=============");

                that.AdjustSearchResultItem(list);

                that.setState({
                    searchResultList: list
                })
            })
        }




    }

    AdjustSearchResultItem = (arr) => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'AdjustSearchResultItem',
                param: [arr]
            }
        });


        arr.forEach(element => {
            element.Active = false;
            element.ImageURL = this.props.baseStore.GetFinalImageUrl(element.ImageURL)
        });
    }

    ChangeShuJia = (index) => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'ChangeShuJia',
                param: [index]
            }
        });

        this.setState({
            activeShuJiaIndex: index
        }, () => {
            this.Search(false);
        })

    }

    ChangeShuTi = (index) => {




        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'ChangeShuTi',
                param: [index]
            }
        });

        this.setState({
            activeShuTiIndex: index
        }, () => {
            this.Search(false);
        })
    }

    ChangeTypeIndex = (index) => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'ChangeTypeIndex',
                param: [index]
            }
        });

        var that = this;
        this.setState({
            typeIndex: index,
            searchInputValue: ''
        }, () => {
            that.Search(false);
        })
    }

    ToggleItemActive = (item) => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'ToggleItemActive',
                param: [item]
            }
        });

        item.Active = !item.Active;
        this.setState({
            searchResultList: this.state.searchResultList
        })
    }


    selectAll = () => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'selectAll',
                param: []
            }
        });

        this.setArrActive(this.state.searchResultList, true);
        this.setState({
            searchResultList: this.state.searchResultList
        })
    }

    unSelectAll = () => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'unSelectAll',
                param: []
            }
        });

        this.setArrActive(this.state.searchResultList, false);
        this.setState({
            searchResultList: this.state.searchResultList
        })
    }

    onSearchInputChange = (value) => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'onSearchInputChange',
                param: [value]
            }
        });

        this.setState({ searchInputValue: value });
    }

    emptySearchResultList = () => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'emptySearchResultList',
                param: []
            }
        });

        this.setState({
            searchResultList: []
        })
    }

    historyClick = (text) => {
        this.setState({ searchInputValue: text });
        setTimeout(() => {
            this.Search(false);
        }, 200);
    }


    handlerConfirm = () => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'handlerConfirm',
                param: []
            }
        });

        var list = [];
        this.state.searchResultList.forEach(x => {
            if (x.Active) {
                list.push(x);
            }
        })
        this.props.showStore.SetRightListDirect(list);
        this.props.history.push('/showCourse');
    }

    handlerConfirmToCreatePage = () => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'handlerConfirmToCreatePage',
                param: []
            }
        });

        // var list = [];
        // this.state.searchResultList.forEach(x => {
        //     if (x.Active) {
        //         list.push(x);
        //     }
        // })
        // this.props.createStore.SetRightListDirect(list);

        this.props.baseStore.topHeader.title = "集字创作";
        this.props.history.push('/entry_02');
    }

    DeleteLinmoWord = (item) => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'DeleteLinmoWord',
                param: [item]
            }
        });

        var that = this;
        // var list = [];
        // this.state.searchResultList.forEach(x => {
        //     if (x.Active) {
        //         list.push(x.DirectoryId);
        //     }
        // })
        // console.log(list, "DeleteLinmoWord");

        Modal.confirm({
            title: '提示',
            content: '确定删除?',
            okText: "确定",
            cancelText: "取消",
            onOk() {

                that.DeleteLinmoWordCb(item.DirectoryId)

            },
            onCancel() {
                console.log('Cancel');
            },
        });


    }

    DeleteLinmoWordCb = (DirectoryId) => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'DeleteLinmoWordCb',
                param: [DirectoryId]
            }
        });


        Service.DeleteLinmoWord(DirectoryId).then(res => {
            that.Search(false);
        });
    }



    showEdit = (item) => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'showEdit',
                param: [item]
            }
        });

        this.setState({
            editEntity: item,
            show_edit: true
        })
    }

    toCreatePage = (item) => {


        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'toCreatePage',
                param: [item]
            }
        });


        if (this.state.typeIndex == 0) {
            this.props.history.push("/creating/" + item.DirectoryId);
        } else {
            var full_url = encode(this.props.baseStore.GetFinalImageUrl(item.ImageURL));
            this.props.history.push("/img_show/" + full_url);
        }


    }

    closeEdit = () => {

        this.props.baseStore.socketData.doEmit("teach_app_to_server", {
            type: "do_action",
            content: {
                action: 'closeEdit',
                param: []
            }
        });

        this.setState({
            show_edit: false
        })
    }

    render() {
        return (
            <div className="Entry02Page page_container animated fadeInDown  fast">

                <div className="mid_container">
                    <div className="one_container">

                        <div className="one_top_line">

                            {
                                this.state.typeList.map((item, index) => {
                                    return (
                                        <div onClick={() => { this.ChangeTypeIndex(index) }} className={index == this.state.typeIndex ? "active" : ''}>{item.name}</div>
                                    )
                                })
                            }

                        </div>
                        <div className="one_input_line">
                            <input className="input_container" onKeyPress={this.handleEnterKey} value={this.state.searchInputValue} onChange={(event) => this.onSearchInputChange(event.target.value)} placeholder={this.state.typeList[this.state.typeIndex].placeholder} />
                            {/* <div className="history_search_container">
                                {
                                    this.state.searchHistoryArr && this.state.searchHistoryArr.map((item, index) => {
                                        return (
                                            <div key={index} className="each_key" onClick={() => { this.historyClick(item) }}>{item}</div>
                                        )
                                    })
                                }
                            </div> */}
                            <div className="search_btn_container" onClick={this.Search}>搜索一下</div>
                        </div>

                    </div>
                    <div className="two_container">
                        <div className="two_each_line">
                            <div className="shu_title">幅式</div>
                            <div className="shu_list">
                                {
                                    this.state.ShuTiList.length > 0 && this.state.ShuTiList.map((item, index) => {
                                        return (
                                            <div className={this.state.activeShuTiIndex == index ? "active" : ''} onClick={() => { this.ChangeShuTi(index) }} key={index}>{item.DirectoryName}</div>
                                        )
                                    })
                                }
                            </div>
                        </div>
                        <div className="two_each_line">
                            <div className="shu_title">字数</div>
                            <div className="shu_list">
                                {
                                    this.state.ShuJiaList.length > 0 && this.state.ShuJiaList.map((item, index) => {
                                        return (
                                            <div className={this.state.activeShuJiaIndex == index ? "active" : ''} onClick={() => { this.ChangeShuJia(index) }} key={index}>{item.DirectoryName}</div>
                                        )
                                    })
                                }
                            </div>
                        </div>
                    </div>

                    <div className="hr"></div>

                    <div className={this.state.searchResultList.length == 0 ? "three_container mt_20 empty" : "three_container mt_20"}>


                        {
                            this.state.searchResultList.length == 0 ? (
                                <div className="empty_container">请输入关键字后搜索</div>
                            ) : null
                        }

                        {
                            this.state.searchResultList && this.state.searchResultList.map((item, index) => {
                                return (
                                    <div className="char_each">
                                        <div className="img_container">
                                            <img src={this.props.baseStore.GetFinalImageUrl(item.ImageURL)} alt="" />
                                        </div>
                                        <div className="char_title_line">
                                            {item.DirectoryName}
                                            {/* <Checkbox className="char_title" onChange={() => { this.ToggleItemActive(item) }} checked={item.Active} >{item.DirectoryName}</Checkbox> */}
                                        </div>
                                        <div class="tool_btn">
                                            {/* <Button type='link' onClick={() => { this.showEdit(item) }}>基本信息</Button> */}

                                            {
                                                this.state.typeIndex == 0 && <Button type='link' onClick={() => { this.DeleteLinmoWord(item) }} >删除</Button>
                                            }

                                            <Button type='link' onClick={() => { this.toCreatePage(item) }}>展示</Button>
                                        </div>


                                    </div>

                                )
                            })
                        }




                    </div>

                    <div className="hr"></div>

                    <div className="four_container">
                        <div className="four_left">
                            <Button type="success" onClick={this.selectAll} className="fl" shape="round" icon="check" size="large">
                                全选
                            </Button>
                            <Button type="default" onClick={this.unSelectAll} shape="round" icon="close" size="large">
                                全返选
                            </Button>
                            <Button type="default" onClick={this.emptySearchResultList} shape="round" icon="delete" size="large">
                                清空
                            </Button>
                            {/* <Button type="default" onClick={this.DeleteLinmoWord} shape="round" icon="delete" size="large">
                                删除
                            </Button> */}

                        </div>

                        {/* <Button className="mr_10" onClick={this.handlerConfirm} type="primary" shape="round" icon="download" size="large">
                            确定
                        </Button>*/}

                        <Button onClick={this.handlerConfirmToCreatePage} type="primary" shape="round" icon="plus" size="large">
                            自由创作
                        </Button>

                    </div>
                </div>

                {
                    this.state.show_edit && (<Modal
                        title={"编辑"}
                        centered={true}
                        width={600}
                        height={400}
                        cancelText="关闭"
                        okText="下载(注：因为白色字,打开可能看不出效果哦)"
                        visible={this.state.show_edit}
                        footer={null}
                        onCancel={this.closeEdit}
                        wrapClassName=""
                    >






                    </Modal>)
                }

            </div >
        )
    }

}

export default loginPage;